package cn.fu.security.md;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;

import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

/**
 * @Title: MyMD.java
 * @Package cn.fu.security.MD
 * @Description: 消息摘要算法加密，一般用于文件完整性，用户注册密码进行消息摘要，不可逆
 * @author zhangxiaofu
 * @Company www.viewhigh.com
 * @date 2016年8月21日 上午1:03:50
 * @version V1.0
 */
public class MyMD {
	private static String src = "99fu";

	public static void main(String[] args) {
		bouncyCastleMD4();
		bouncyCastleMD5();
		commonsCodesMD5();
		commonsCodesMD2();
	}

	// public static void bouncyCastleMD4() {
	// MD4Digest digest = new MD4Digest();
	// digest.update(src.getBytes(), 0, src.getBytes().length);
	// byte[] md4Bytes = new byte[digest.getDigestSize()];
	// digest.doFinal(md4Bytes, 0);
	// System.err.println(Hex.toHexString(md4Bytes));
	// }
	// 使用jdk动态添加provider,当然也可以用jdk lib中 用配制文件添加
	public static void bouncyCastleMD4() {
		try {
			Security.addProvider(new BouncyCastleProvider());
			MessageDigest md = MessageDigest.getInstance("MD4");
			Provider provider = md.getProvider();
			System.err.println(provider);// BC version 1.54
			byte[] md4Bytes = md.digest(src.getBytes());
			System.err.println("bcMD4:" + Hex.toHexString(md4Bytes));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	public static void bouncyCastleMD5() {
		MD5Digest digest = new MD5Digest();
		digest.update(src.getBytes(), 0, src.getBytes().length);
		byte[] md5Bytes = new byte[digest.getDigestSize()];
		digest.doFinal(md5Bytes, 0);
		System.err.println("bcMD5:" + Hex.toHexString(md5Bytes));
	}

	public static void commonsCodesMD5() {
		String md5Hex = DigestUtils.md5Hex(src.getBytes());
		System.err.println("ccMD5:" + md5Hex);
	}

	public static void commonsCodesMD2() {
		String md2Hex = DigestUtils.md2Hex(src.getBytes());
		System.err.println("ccMD2:" + md2Hex);
	}
}
